<template>
   <div class="mainList">
    <div class="searchMain">
      <div class="searchPos" :class="{'boxShow': searchHide}">
        <a-form ref="formSearchRef" :model="formSearch" v-if="columnsDistShow">
          <div class="form-main" :class="{'searchHide': searchHide}">
            <div class="form-item">
              <div class="searchTop-list tess">
                <a-select v-model="formSearch.keywords_type"
                      style="width:165px"
                      :trigger-props='{trigger:"hover"}'
                      :bordered="false"
                      :options="keywordTypes"
                      default-value="id"
                      @change="(v)=>switchKeywordType(formSearch,v)">
                </a-select>
                <a-input v-model="formSearch[formSearch['keywords_type']??'id']" allow-clear placeholder="请输入单号"/>
              </div>
            <a-form-item field="keywords_type" label="单号" label-col-flex="90px"style="display: none;"></a-form-item>
            <a-form-item field="shipment_no" label="单号" label-col-flex="90px"style="display: none;"></a-form-item>
            <a-form-item field="id" label="单号" label-col-flex="90px"style="display: none;"></a-form-item>
            <a-form-item field="send_date" label="发出时间" label-col-flex="90px" class="searchTop-list">
              <a-date-picker    
                show-time
                format="YYYY-MM-DD HH:mm:ss"                   
                v-model="formSearch.send_date"               
              />
            </a-form-item>
            <a-form-item field="type" label="类型" label-col-flex="90px" class="searchTop-list">
              <a-select v-model="formSearch.type" :max-tag-count="1"
                        placeholder="请选择类型" allow-clear>
                <a-option :value="1">大货</a-option>
                <a-option :value="2">包裹</a-option>
              </a-select>
            </a-form-item>
            <a-form-item field="get_date" label="接收时间" label-col-flex="90px" class="searchTop-list">
              <a-date-picker    
                show-time
                format="YYYY-MM-DD HH:mm:ss"                   
                v-model="formSearch.get_date"               
              />
            </a-form-item>
            <a-form-item field="clearance" label="单独清关" label-col-flex="90px" class="searchTop-list" >
            <a-select v-model="formSearch.clearance" :max-tag-count="1"
                        placeholder="请选择是否单独清关" allow-clear>
              <a-option :value="1">是</a-option>
              <a-option :value="0">否</a-option>
              </a-select>
          </a-form-item>
          <a-form-item field="declaration" label="出口报关" label-col-flex="90px" class="searchTop-list" >
            <a-select v-model="formSearch.declaration" :max-tag-count="1"
                      placeholder="请选择是否出口报关" allow-clear>
            <a-option :value="1">是</a-option>
            <a-option :value="0">否</a-option>
            </a-select>
          </a-form-item>
            <a-form-item field="supplier_service_id" label="供应商服务" label-col-flex="90px" class="searchTop-list">
                  <a-select v-model="formSearch.supplier_service_id" :max-tag-count="1" :options="columnsDist.dicthelpApi_supplier.data" :field-names="{ value: 'id', label: 'name' }"
                  placeholder="请选择供应商服务" allow-clear allow-search :virtual-list-props="{height:200}">            
                    </a-select>
            </a-form-item>
          </div>
        
            <div class="form-buttom">
              <div>
                <a-button type="primary" html-type="submit" @click="submitSearch" style="margin-right: 10px;">
                  <template #icon>
                    <icon-search/>
                  </template>
                  搜索
                </a-button>
                <a-button @click="resetSearch">
                  <template #icon>
                    <icon-delete/>
                  </template>
                  重置
                </a-button>
              </div> 
              <a-space class="lg:mt-0 mt-2" style="margin-top: 20px;display: flex;justify-content: flex-end;margin-right: 10px">         
                  <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide"  style="margin-right: 10px"><icon-search/></a-button></a-tooltip>
                  <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
                </a-space>                        
            </div>
          </div>
        
          <div class="touHide" style="display: flex;justify-content: center;margin-bottom: 10px;">  
            <a-link v-if="searchHide" @click="searchHide=!searchHide" size="small">
              {{ searchHide ? '收起':'' }}
              <template #icon>
                <icon-up v-if="searchHide" />
              </template>
            </a-link>
          </div>
          </a-form>
      </div>
    </div>
    <div class="ma-content-block justify-between p-4 mainTable">
      <!-- 操作按钮 -->
      <div class="top-button">
            <div>
                <a-button type="primary" @click="addAction()">
              <template #icon>
                <icon-plus/>
              </template>
              新增
            </a-button>
            <download url="warehouse/delivery/export" type="delivery"/>
            </div>
        <a-space class="lg:mt-0 mt-2">         
          <a-tooltip content="显隐搜索"><a-button shape="circle" @click="searchHide=!searchHide" ><icon-search/></a-button></a-tooltip>
          <a-tooltip content="设置"><a-button shape="circle" @click="openSetting"><icon-settings/></a-button></a-tooltip>
        </a-space>
            
        </div>
        <!-- tab切换 -->
        <a-tabs class="ma-tabs mb-1 tabs" @change="clickTap" v-model:active-key="formSearch.status">         
          <a-tab-pane :key="item.key" :title="item.title" v-for="item in shipmentTabs">
            <template #title>
              <slot :name="'tabTitle-' + item.label">{{ item.title }}{{ item.count ? `(${item.count})` : '' }}</slot>
            </template>
          </a-tab-pane>
      </a-tabs>
      <!-- 状态按钮 -->
      <div style="display: flex;">
        <button-group :button-groups="buttonGroups" :dataList="dataList" :crud-ref="crudRef" :selected="selected"
        :currentStatus="currentStatus"/>
        <slot>
            <a-button 
            @click="merge()" size="small" type="primary" v-show="isButtonShow({show:['1']})"
            class="w-full lg:w-auto mt-2 lg:mt-0"
            >
              合并
            </a-button>
          </slot>
      </div> 
      <div ref="tablePrantRef">
        <a-table ref="tableRef" :sticky-header="true" :scrollbar="true" :stripe="true" :scroll="{ x: '100%', y: '100%' }"  :columns="localColumns(columnsData)" :data="dataList" class="table-list" 
          hide-expand-button-on-empty :loading="loading" row-key="id" v-model:selectedKeys="selected" @selection-change="setSelecteds($event)" stripe :row-selection="rowSelection" column-resizable :pagination="false">
      <!--  列表插槽    -->
      <template #tr="{ record }">
                <tr
            class="ma-crud-table-tr"
            @dblclick="editAction(record)"
        />
      </template>
        <template #id="{ record }">
          <a-link color="blue" @click="editAction(record)">{{ record.id }}</a-link>
        </template>
        <template #type="{ record }">
          <div v-if="record.type=='1'">大货</div>
          <div v-else-if="record.type=='2'">包裹</div>
        </template>
        <template #clearance="{ record }">
          <div v-if="record.clearance=='1'">是</div>
          <div v-else-if="record.type=='0'">否</div>
        </template>
        <template #declaration="{ record }">
          <div v-if="record.declaration=='1'">是</div>
          <div v-else-if="record.type=='0'">否</div>
        </template>
        
        <template #from_depot_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_depot',record.from_depot_id,3,columnsDist) }}</template>
        <template #to_depot_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_depot',record.to_depot_id,3,columnsDist) }}</template>
        <template #status="{ record }" v-if="columnsDistShow">{{getDictData('dictObj','DeliveryStatus',record.status,2,columnsDist) }}</template>
        <template #supplier_service_id="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_supplier',record.supplier_service_id,3,columnsDist) }}</template>
        <template #created_by="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.created_by,4,columnsDist) }}</template> 
        <template #updated_by="{ record }" v-if="columnsDistShow">{{getDictData('attrApi','dicthelpApi_user',record.updated_by,4,columnsDist) }}</template> 
        <template #flex="{ record }" v-show="isButtonShow({show:[5]})">
          <a-link @click="turn(record)" v-if="currentStatus == 5" v-auth="['document:delivery:turn']"> 转运</a-link>
          <a-link @click="openTray(record)"  v-if="currentStatus == 5" v-auth="['document:delivery:tray']"> 托盘</a-link>
        </template>
      </a-table>
      </div>
    <!-- 分页 -->
    <div class="foot-list">
      <a-pagination
          :total="pageInfo.total"
          show-total show-jumper show-page-size     
          v-model:current="formSearch.page"
          @change="pageChange"
          @page-size-change="pageSizeChange"
          :page-size-options="[10, 20, 30, 50, 100]"
          :page-size="formSearch.pageSize"
          style="display: inline-flex"
      />
    </div>
    <batch-action-modal v-model="batch.visible"
    :crud-ref="crudRef"
    :selected="selected"
    ref="batchActionRef"
    ></batch-action-modal>
    <delivery-info ref="deliveryInfo" />
    <add-modal-form ref="addModalMormRef" @addClick="tableList" v-if="columnsDistShow"></add-modal-form>
    <add-modal ref="addModalRef"></add-modal>
    <tray-modal ref="trayModal"></tray-modal>
    <setting ref="settingRef"></setting>
  </div>
</div>
</template>
<script setup>
import { ref, reactive ,provide,computed,watch,onMounted} from 'vue'
import delivery from '@/api/warehouse/delivery'
import { Message } from '@arco-design/web-vue'
import DeliveryInfo from './info.vue'
import AddModal from "@cps/actionsNew/addModal.vue";
import AddModalForm from "@/views/warehouse/delivery/components/addModalForm.vue";
import TrayModal from "./components/tray.vue";
import {getDictData} from "@/utils/crud/dictNew.js";
import BatchActionModal from "@cps/actionsNew/batchActionModal.vue";
import tag from '@/api/logistics/tag'
import ButtonGroup from "@cps/actionsNew/buttonGroup.vue";
import Download from "@/views/components/downloadNew.vue";
import dicthelpApi from "@/api/dicthelpApi.js";
import common from "@/api/common.js";
import Setting from "@/views/components/setting.vue";
import {localColumns,tablePrantRefHeight} from "@/utils/crud/culmns.js";

const crudRef = ref()
const deliveryInfo = ref()
const addModalRef = ref()
const addModalMormRef = ref()
const trayModal = ref()
const batchActionRef = ref()
const batch = ref({visible:false,})
const selected=ref([])
const columnsDistShow=ref(false)
const shipmentTabs=ref([])//tabs赋值
const countList=ref({})
const tableRef = ref()
const tablePrantRef = ref() //tabel 父级高度
const dataList = ref([])
const loading=ref(false)
//搜索更多是否显示
const searchHide=ref(false)

watch([shipmentTabs,countList],
(newValues) => {
  if(shipmentTabs.value!='' && countList.value!=''){
      shipmentTabs.value.forEach(function(item) {
            item.count = countList.value[item.key] ? countList.value[item.key] : 0
      })   
  }
  }
)
const currentStatus = computed(() => {
  let requestParams = formSearch
  if (!requestParams.status) {
    return null;
  }
  return requestParams.status
})
const columnsData = ref([  
{title: '出货单号', dataIndex: 'id',slotName: 'id',width:180,hide:true,},
{title: '参考号', dataIndex: 'reference',width:150,align:'center',hide:true,},
{title: '发出时间', dataIndex: 'send_date',width:90,align:'center',hide:true,},
{title: '类型', dataIndex: 'type',slotName: 'type',width:70,align:'center',hide:true,},
{title: '箱数', dataIndex: 'volume_weight.parcel_count',width:100,align:'center',hide:true,},
{title: '发出站点', dataIndex: 'from_depot_id',slotName: 'from_depot_id',width:100,align:'center',hide:true,},
{title: '发往站点', dataIndex: 'to_depot_id',slotName: 'to_depot_id',width:100,align:'center',hide:true,},
{title: '状态', dataIndex: 'status',slotName: 'status',align:'center',width:100,hide:true,},
{title: '重量', dataIndex: 'volume_weight.weight',width:100,align:'center',hide:true,},
{title: '体积/泡比', dataIndex: 'volume_weight.ratio',width:100,align:'center',hide:true,},
{title: '体积比', dataIndex: 'volume_weight.volume_ratio',width:100,align:'center',hide:true,},
{title: '主品名', dataIndex: 'name',width:100,align:'center',hide:true,},
{title: '接收时间', dataIndex: 'get_date',width:90,align:'center',hide:true,},
{title: '单独清关', dataIndex: 'clearance',slotName: 'clearance',width:100,align:'center',hide:true,},
{title: '出口报关', dataIndex: 'declaration',slotName: 'declaration',width:100,align:'center',hide:true,},
{title: '标识', dataIndex: 'tags',slotName: 'tags',width:70,align:'center',hide:true,
    render: ({record}) => {
      if(columnsDistShow && record.tags.length>0 && columnsDist.value.dicthelpApi_tagsType){
        let attrsObj=getDictData('tags','dicthelpApi_tagsType',record.tags,3,columnsDist.value)
        attrsObj= attrsObj.children.filter(person => person.type);
        return attrsObj
      }
    }

  },
{title: '分货备注', dataIndex: 'distribut_mark',width:150,align:'center',hide:false,},
{title: '供应商服务', dataIndex: 'supplier_service_id',slotName: 'supplier_service_id',align:'center',width:150,hide:false,},
{title: '创建者', dataIndex: 'created_by',slotName: 'created_by',width:150,align:'center',hide:false,},
{title: '更新者', dataIndex: 'updated_by',slotName: 'updated_by',width:150,align:'center',hide:false,},
{title: '创建时间', dataIndex: 'created_at',width:90,align:'center',hide:false,},
{title: '更新时间', dataIndex: 'updated_at',width:90,align:'center',hide:false,},
{title: '删除时间', dataIndex: 'deleted_at',width:90,align:'center',hide:false,},
{title: '备注', dataIndex: 'remark',width:80,align:'center',hide:false,},
{title: '操作', dataIndex: 'flex',slotName: 'flex',fixed: 'right',width:150,align:'center',hide:true,},
]);

const settingRef = ref()
const openSetting=()=>{
  settingRef.value.open()
}
//新增
const addAction=()=>{
  console.log('jjjjjjjjj',addModalMormRef.value)
  addModalMormRef.value.onShow()
}
//详情
const editAction=(record)=>{
  deliveryInfo.value.open(record)
}

//总页数
const pageInfo = ref({
  currentPage: 1,
  total: 0,
  totalPage:1
})

//table 选择
const rowSelection = reactive({
  type: 'checkbox',
  showCheckedAll: true,
  checkStrictly: true
});


//列表请求数据
const formSearch=reactive({
  type:[],
  clearance:[],
  declaration: [],
  reference: [],
  supplier_service_id:[],
  refresh_tabs: 1,
  page: 1,
  pageSize: 10,
  keywords_type: 'id',
  status: '1',
  })
  //下拉框全选
const handleSelectAll = (status,list,type,typeStus) => {
  if (isUndefined(formSearch[type])) {
    formSearch[type] = []
  }
  if (status) {
    let value=[]
    list.map(item => {
      value.push(item[typeStus])
    })
    formSearch[type]=value
  } else {
    formSearch[type] = []
  }
}
//下拉框反选
const handleInverse = (list,type,typeStus) => {
  if (isUndefined(formSearch[type])) {
    formSearch[type] = []
  }
  const ids = []
  list.map(item => ids.push(item[typeStus]))
  formSearch[type] = xor(ids, formSearch[type])
}
  const formSearchRef=ref(null)
    //重置
  const resetSearch=(e)=>{
    formSearchRef.value.resetFields();
    console.log('formSearch',formSearch)
    tableList()
  }
 //搜索 
 const submitSearch=(e)=>{
  formSearch.page=1
  formSearch.refresh_tabs=1
  searchHide.value=false
  tableList()
}

  //切换分页
const pageChange=(e)=>{
  if(e){
   formSearch.page=e
    tableList()
  }
}
  //切换条数
const pageSizeChange=(e)=>{
  if(e){
   formSearch.pageSize=e
    tableList()
  }
}
//行数选中
const setSelecteds = (key) => {
  selected.value = key
}
//tabs切换
const clickTap=(e)=>{
  formSearch.page=1
  formSearch.status=e
  formSearch.refresh_tabs=0
    tableList()
}
    //列表
    const tableList = () => {
      loading.value=true
      delivery.getList(formSearch).then(res => {     
        dataList.value =  res.data.items
        //页数
        pageInfo.value = res.data.pageInfo
        countList.value=res.data.count     
        formSearch.status=res.data.current_type.toString()
        selected.value=[]
        loading.value=false
        tablePrantRefHeight(tablePrantRef.value)
      })      
    }
  
    onMounted(() => {
      tableList()
    })


const buttonGroups = [
  {title:'出货',auth:['document:delivery:changedeliveryStatus'],api:delivery.out,displayDataIndex:"id",hideStatus:["2","3","4","5","6"]},
  {title:'回退',auth:['document:delivery:changedeliveryStatus'],api:delivery.back,displayDataIndex:"id",hideStatus:["1","3","4","5","6"]},
  {title:'接收',auth:['document:delivery:changedeliveryStatus'],api:delivery.receive,displayDataIndex:"id",hideStatus:["2","3","1","5","6"]},
  {title:'标识',action:'',AuditShow:true,api:tag.set,
        form:{
            form:{
              about_type:3
            },
            columns:[
              {title: '操作', dataIndex: 'type',formType: 'select',dict:{
                  data:[
                    {label:'添加',value:1},
                    {label:'移除',value:2},
                    {label:'设置',value:3},
                    {label:'清除全部',value:4},
                  ]
                },
                commonRules: {
                    required: true,
                    message: "请选择操作类型"
                },
              },
              {title: '标识', dataIndex: 'tag_ids',formType: 'checkbox',dict:{
                    url: 'logistics/tag/list',
                    props: {label: 'name', value: 'id'},
                    translation: true,
                    params: {select: 'id,name',type:3},
                },
              },

            ]
          },
        },
        
  {title:'审计',auth:['document:delivery:audit'],api:delivery.auditPass,displayDataIndex:"id",
  form:{
        columns:[
          {title: '操作', dataIndex: 'types',formType: 'checkbox',dict:{
            data:[
              {label:'应付-仅流水',value:3},
              {label:'应付-提单及流水',value:4},
            ]
          },
            commonRules: {
                    required: true,
                    message: "请选择操作类型"
                },
          },
        ]
      },
  },
  {title:'反审计',auth:['document:delivery:audit'],api:delivery.auditRefuse,displayDataIndex:"id",
  form:{
        columns:[
          {title: '操作', dataIndex: 'types',formType: 'checkbox',dict:{
            data:[
              {label:'应付-仅流水',value:3},
              {label:'应付-提单及流水',value:4},
            ]
          },
            commonRules: {
                    required: true,
                    message: "请选择操作类型"
                },
          },
        ]
      },
  },
  {title:'删除',status:'danger',auth:['document:delivery:delete'],api:delivery.deletes
  ,hideStatus:["2","3","4","5","6"]
  },
]
const keywordTypes = [
  //  转单号   供应商单号
  {value: 'id', label: '出货单号'},
  {value: 'shipment_no', label: '运单号'},
]
const switchKeywordType = (form,value)=>{
  keywordTypes.map(i=>{
    if(form[i.value] && i.value !== value){
      form[value] = form[i.value]
      form[i.value] = undefined
    }
  })
}
const openTray = (record)=>{
  trayModal.value.open(record)
}
const isButtonShow = (button,test)=>{
  return button.show.includes(currentStatus.value)
}

const turn = (record)=>{
  record.turn =true
  addModalMormRef.value.onShow(record)
}

const merge = ()=>{
  if(selected.value.length == 0){
    Message.warning('请选择要合并的记录')
    return
  }
  if(selected.value.length == 1){
    Message.warning('请选择多条记录合并')
    return
  }
  let dicts = [];
  for (let index = 0 ; index < selected.value.length; index++) {
    dicts.push({label:selected.value[index],value:selected.value[index]})
  }
  addModalRef.value.open(
     reactive([
        {
            title: "合并至",
            dataIndex: "id",
            dict:{
              data:dicts,
            },
            formType: "radio",
        },
        {
          dataIndex:'ids',
          formType: "input",
          disabled:true,
          addDefaultValue: selected.value
        }
    ]) , {
    viewType: 'modal',
    width: '70%',
    layout: [],
  }, delivery.merge,'合并运单',function name(params) {
      crudRef.value.refresh()
  })
}

const deliveryColumns= async (crudRef) => {
  let attrDict=['DeliveryStatus','currencyType','ChargeType']
  let [dictObj,dicthelpApi_depot,dicthelpApi_supplier,dicthelpApi_tagsType,dicthelpApi_feeTypeList,dicthelpApi_user]=await Promise.all([
    common.getDicts(attrDict),dicthelpApi.depot(),dicthelpApi.supplier(),dicthelpApi.tagsType(3),dicthelpApi.feeTypeList({select: 'id,fee_name',cate:7}),dicthelpApi.user()
    ])

  return reactive({
    dictObj,
    dicthelpApi_depot,
    dicthelpApi_supplier,
    dicthelpApi_tagsType,
    dicthelpApi_feeTypeList,
    dicthelpApi_user
  })
}
const columnsDist = ref([])
const dictList = ref({})
const feeTypeList = ref({})
const supplierList = ref({})
deliveryColumns(crudRef).then(res=>{
  console.log('jjjjjjjjjjjj',res)
  columnsDist.value=res
  dictList.value=res.dictObj.data
  feeTypeList.value=res.dicthelpApi_feeTypeList.data
  supplierList.value=res.dicthelpApi_supplier.data
  columnsDistShow.value=true
  let parcelType=res.dictObj.data.DeliveryStatus
  if(parcelType){
    shipmentTabs.value=parcelType
  }
})
provide('tableList',tableList);
provide('getDictData', getDictData)
provide('crudRef',crudRef)
provide('dictList', dictList) //全部字典
provide('columnsData', columnsData)
provide('columnsDist', columnsDist)
provide('selected', selected)
provide('dataList', dataList)
provide('formSearch', formSearch)
provide('feeTypeList', feeTypeList) //费用类型
provide('supplierList', supplierList) //供应商
</script>
<script> export default { name: 'warehouse:delivery' } </script>
<style>
.form-inline-card > .arco-card-body {
  padding: 0;
  display: grid;
  grid: 1fr / 1fr 1fr 1fr;
}

.form-inline-card > .arco-card-header {
  display: none;
}

.fee-up {
  border-bottom: dashed #777777 1px;
}

.fee-down {
  color: orange;
}
.customer-input-item .arco-btn-group button:first-child{
  display:none;
}
/* .searchTop{
  display: flex;
  align-content: center;
  flex-direction:row;
  flex-wrap: wrap;
} */
.form-main{
  display: flex;
  height: 40px;
  overflow: hidden;
}
.searchHide{
  height: auto;
}
.boxShow{
  box-shadow: 0 10px 10px 10px #ccc;
}
.form-item{
  display: flex;
  flex-direction:row;
  flex-wrap: wrap;
  flex: 1;
}
.form-buttom{
  margin-left:20px;
  width:200px;
}
.searchTop-list{
  width: 20%;
}
.searchTop-list.tess{
  display: flex;
  margin-bottom: 20px;
}
@media (min-width: 601px) and (max-width: 1300px){
		.searchTop-list{
       width: 50%;
		}
}
@media (min-width: 1301px) and (max-width: 1700px){
		.searchTop-list{
       width: 33.33%;
		}
}
.top-button{
  display: flex;
  justify-content: space-between;
}
.top-button button{
  margin-right: 10px;
}
.table-list{
  margin-top:5px;
}
.arco-tabs-content{
  padding:0;
}
.foot-list{
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.searchMain{
  position: relative;
}
.searchPos{
  position: absolute;
  left: 0;
  width: 100%;
  top: 0;
  z-index: 800;
  padding: 1rem 1rem 0;
  background: #ffffff;
}
.mainTable{
  padding-top: 68px;
}
.arco-select-view-inner{
  white-space: nowrap;
}
.arco-select-view-inner .arco-tag{
  white-space: nowrap !important;
}
.tabs .arco-tabs-tab{
  min-width: 70px;
  justify-content: center;
}
</style>